import { resolve, join } from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import legacy from "@vitejs/plugin-legacy";
import autoprefixer from "autoprefixer";

export default defineConfig(({ mode }) => {
    // js兼容性
    const jsplugins = "production"
        ? [
            legacy({
                targets: ["defaults", "not IE 11"],
                additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
                renderLegacyChunks: true,
            }),
        ]
        : [];
    // css兼容性
    const cssplugins =
        mode == "production"
            ? [
                autoprefixer({
                    overrideBrowserslist: ["defaults", "not IE 11"],
                    grid: true,
                    flexbox: true,
                }),
            ]
            : [];

    return {
        root: "./src/",
        base: "./",
        publicDir: "./src/assets/",
        server: {
            open: true,
            port: 2024,
        },
        plugins: [react(), ...jsplugins],
        resolve: {
            extensions: [".jsx", ".js", ".scss"],
            alias: {
                "@": join(__dirname, "./src"),
            },
        },
        css: {
            devSourcemap: true,
            postcss: {
                plugins: cssplugins,
            },
            // scss全局变量配置
            preprocessorOptions: {
                scss: {
                    javascriptEnabled: true,
                    additionalData: '@import "./src/styles/varuable.scss";',
                },
            },
        },
        build: {
            outDir: resolve(__dirname, "./build"),
            emptyOutDir: true,
            sourcemap: true,
            rollupOptions: {
                output: {
                    chunkFileNames: "js/[name].js",
                    entryFileNames: "js/[name]-[hash].js",
                    assetFileNames: (asset) => {
                        if (asset.name.includes(".css")) {
                            return "style/[name]-[hash].css";
                        } else {
                            return "assets/[name].[ext]";
                        }
                    },
                    manualChunks: {
                        vendor: ["react", "react-dom"],
                    },
                },
            },
        },
    };
});
